import * as React from 'react'
import { Config, User } from '../../../serve/interface';
import { Select, Spin } from 'antd';
const { Option } = Select;

declare var __all_config__: Partial<Config>;
const { store } = __all_config__

function debounce(fn, delay) {
    var ctx;
    var args;
    var timer = null;

    var later = function () {
        fn.apply(ctx, args);
        // 当事件真正执行后，清空定时器
        timer = null;
    };

    return function () {
        ctx = this;
        args = arguments;
        // 当持续触发事件时，若发现事件触发的定时器已设置时，则清除之前的定时器
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }

        // 重新设置事件触发的定时器
        timer = setTimeout(later, delay);
    };
}

interface Props { onChange: (user: User) => void }
interface State {
    data: { name: string, displayName: string }[],
    fetching: boolean
}
/**
 * @see https://ant-design.gitee.io/components/select-cn/#components-select-demo-select-users
 */
export default class extends React.Component<Props, State> {
    constructor(props: Props) {
        super(props);
        this.fetchUser = debounce(this.fetchUser, 800);
    }

    state: State = {
        data: [],
        fetching: false,
    };

    fetchUser = (value: string) => {
        this.setState({ data: [], fetching: true });
        fetch(`${store.apiRoot}/rest/api/2/user/search?username=${value}`)
            .then(response => response.json())
            .then((data: {name: string, displayName: string}[]) => {
                this.setState({ data, fetching: false });
            });
    };

    handleChange = (item: any) => {
        this.props.onChange({
            name: item.value,
            nickname: item.label,
            password: '',
        })
        this.setState({
            data: [],
            fetching: false,
        });
    };

    render() {
        const { fetching, data } = this.state;
        return (
            <Select
                labelInValue
                placeholder="输入关键字检索"
                notFoundContent={fetching ? <Spin size="small" /> : null}
                filterOption={false}
                showSearch
                onSearch={this.fetchUser}
                onChange={this.handleChange}
                style={{ width: '100%' }}
                options={data.map(item => ({ value: item.name, label: item.displayName }))}
            />
        );
    }
}